package com.example.testapp.utils;

import android.graphics.Bitmap;
import android.util.Base64;
import android.util.Log;

import com.example.testapp.api.ApiConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BaiduOcrHelper {
    private static final String TAG = "BaiduOcrHelper";
    private static final String API_KEY = ApiConfig.getApiKey();
    private static final String SECRET_KEY = ApiConfig.getSecretKey();
    private static final String OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
    private static final String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder()
            .readTimeout(60, TimeUnit.SECONDS)
            .build();

    /**
     * 将Bitmap转换为Base64字符串
     */
    public static String bitmapToBase64(Bitmap bitmap) {
        // 计算合适的分辨率 (最大2000px)
        int maxDimension = 2000;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        if (width > maxDimension || height > maxDimension) {
            float ratio = (float) width / height;
            if (width > height) {
                width = maxDimension;
                height = (int) (width / ratio);
            } else {
                height = maxDimension;
                width = (int) (height * ratio);
            }
            bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
        }

        // 压缩图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int quality = 80;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);

        // 确保图片大小 < 4MB
        while (outputStream.toByteArray().length > 3 * 1024 * 1024 && quality > 40) {
            outputStream.reset();
            quality -= 10;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        }

        byte[] byteArray = outputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.NO_WRAP); // 使用NO_WRAP避免换行符
    }

    /**
     * 获取百度API访问令牌
     */
    public static String getAccessToken() throws IOException {
        Log.d(TAG, "getAccessToken: 开始获取百度API访问令牌");
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String content = "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;
        RequestBody body = RequestBody.create(mediaType, content);

        Request request = new Request.Builder()
                .url(TOKEN_URL)
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                Log.e(TAG, "getAccessToken: 获取访问令牌失败，HTTP状态码=" + response.code());
                return null;
            }

            String responseBody = response.body().string();
            JSONObject json = new JSONObject(responseBody);
            return json.getString("access_token");
        } catch (JSONException e) {
            Log.e(TAG, "getAccessToken: JSON解析异常: " + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 调用百度OCR API识别文本
     */
    public static String recognizeText(String base64Image) throws IOException {
        Log.d(TAG, "recognizeText: 开始调用百度OCR API");
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        // 获取访问令牌
        String accessToken = getAccessToken();
        if (accessToken == null) {
            Log.e(TAG, "recognizeText: 无法获取访问令牌");
            return null;
        }

        // 对Base64数据进行URL编码
        String encodedImage = URLEncoder.encode(base64Image, "UTF-8");

        // 构建请求体
        String requestBody = "image=" + encodedImage +
                "&language_type=CHN_ENG" +
                "&detect_direction=true" +
                "&paragraph=true" +
                "&probability=false";

        Request request = new Request.Builder()
                .url(OCR_URL + "?access_token=" + accessToken)
                .post(RequestBody.create(mediaType, requestBody))
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                Log.e(TAG, "recognizeText: OCR API请求失败，HTTP状态码=" + response.code());
                return null;
            }
            return response.body().string();
        }
    }
}